package com.mjk.manager.workflow.component;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;

import com.mjk.common.base.work.annotation.BeeWork;
import com.mjk.common.tools.lambada.LambdaReflectionUtil;
import com.mjk.common.tools.springextend.BeeApplicationListener;
import com.mjk.common.util.*;
import com.mjk.manager.workflow.component.dto.BeeLiteFlowContext;
import com.yomahub.liteflow.slot.DefaultContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.ssssssss.script.MagicScriptContext;


/**
 * 业务流基类
 * @author Administrator
 *
 */

public interface BaseFlow extends BeeApplicationListener {
	Map<String,Object> flowMap = new HashMap<>();
	
	@Override
	default void doApplicationEvent(ContextRefreshedEvent event) {
		Map<String,Object> works = event.getApplicationContext().getBeansWithAnnotation(BeeWork.class);
		for(Entry<String,Object> entry : works.entrySet()){
			Object target = AopTargetUtils.getTarget(entry.getValue());
			BeeWork work = Objects.requireNonNull(target).getClass().getAnnotation(BeeWork.class);
			//if(work.isFlow()) { //动态编译产生代理类
				flowMap.put(work.work(),target);
			//}
		}
	}

	/**
	 * 把流中传递的第一个参数转化为MagicScriptContext
	 * @param obj
	 * @return
	 */
	default MagicScriptContext conver2Context(BeeLiteFlowContext obj){
		MagicScriptContext context = new MagicScriptContext();
		for(Entry<String,Object> entry : obj.getDataMap().entrySet()){
			context.set(entry.getKey(),entry.getValue());
		}
		return context;
	}

	/**
	 * 参数转化
     */
	default <T> T conver2Paramters(DefaultContext context, Class<T> clazz) {
		Object o = ReflectionUtils.newInstance(clazz);
		Field[] fields = ReflectionUtils.getFields(o.getClass());
		for(Field f : fields) {
			if(context.hasData(f.getName())) {
				LambdaReflectionUtil.invoke(o,"set"+StrUtils.toUpperCaseFirstOne(f.getName()), BeanUtils.toBean(context.getData(f.getName()),f.getType()));
			}
		}
		return (T)o;
	}
}
